﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using WinHBM.Core.Net.Http;
using System.Threading;

namespace WinHBM.Core.Net.Sockets.Cmd
{
    /*[Serializable]
    public class UserInfo
    {
        public string loginId;
        public string password;
        public bool auto;
        public string address;
        public int userId;
    }*/

    public class LoginCmd : SocketCmd
    {

        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(LogCmd));

        private HttpClient client = HttpClient.Instance;


        

        public override void executeCmd(JObject request,FlashSocketServer socket)
        {

            /*if(TokenHolder.isLogin)
            {
                return;
            }*/

            string mobile = request["mobile"].ToString();
            string password = request["password"].ToString();
            bool remember = (bool)request["remember"];
            bool auto = (bool)request["auto"]; 
            JObject requestBody = new JObject();
            requestBody["login_id"] = mobile;
            requestBody["password"] = password;
            requestBody["role"] = "teacher"; 
            client.CreateRequest("/api/auth/login", RequestMethod.POST, requestBody)
                .send((response, data) => {
                    if(data["errcode"].ToString() != "0")
                    {
                        socket.Send(wrapCmd(CMD_LOGIN, data["message"].ToString()));
                        return;
                    }
                    //存储Token
                    string token = data["contents"]["token"].ToString();
                    int userId = Convert.ToInt32(data["contents"]["user_id"].ToString());
                    int classId = Convert.ToInt32(data["contents"]["class_id"].ToString());
                    TokenHolder.Token = token;
                    TokenHolder.isLogin = true;
                    //存储用户信息

                    UserInfo userInfo = UserInfo.INSTANCE;

                    //FileStream fs = new FileStream("user.bin", FileMode.OpenOrCreate);
                    //UserInfo userinfo = new UserInfo();
                    userInfo.Id = userId;
                    userInfo.LoginId = mobile;
                    userInfo.ClassId = classId;
                    //记住密码
                    if (remember)
                    {
                        userInfo.Password = password;
                        if(auto)
                        {
                            userInfo.Auto = auto;
                        }
                    }

                    userInfo.commit();
                    Thread taskThread = new Thread(Bootstrap.TaskThread);
                    taskThread.Start();
                    //发送响应数据给Flash
                    socket.Send(wrapCmd(CMD_LOGIN,data));
                }, (response, exception) => {
                    
                    if(exception != null)
                    {
                        socket.Send(wrapCmd(CMD_LOGIN, exception.Message));
                        Logger.Error(exception);
                        return;
                    }

                    if(response != null)
                    {
                        socket.Send(wrapCmd(CMD_LOGIN, "请求错误码:"+((int)response.StatusCode)));
                        return;
                    }

                });
        }
    }
}
